package com.irdstudio.apicenter.frame.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.irdstudio.apicenter.frame.core.jdbc.JdbcBaseDAO;
import com.irdstudio.apicenter.frame.core.jdbc.container.UniKeyValueObject;
import com.irdstudio.apicenter.frame.util.BeanUtils;

/**
 * 数据字典服务
 * 
 * @author zs.ligm
 * @version 1.0
 * @date 2015-06-30
 */
@Service
public class DataDicService extends AbstractService {

	/* 字典缓存区 */
	private static Map<String, UniKeyValueObject> dicBuffer = null;;

	@Override
	public String getName() {
		return "DataDicService";
	}

	/**
	 * 启动时将数据字典数据加载到缓存
	 */
	@Override
	public void start() {

		this.logger.info("从数据库中加载s_dic表...");

		dicBuffer = new HashMap<String, UniKeyValueObject>();

		// 从数据库中读取数据到缓存区
		JdbcBaseDAO baseDao = BeanUtils.getBean(JdbcBaseDAO.class);
		List<Map<String, Object>> dicItems = baseDao.findMapList(
				"select opttype from s_dic group by opttype", null);

		for (int i = 0; i < dicItems.size(); i++) {
			Map<String, Object> dic = dicItems.get(i);
			List<Map<String, Object>> items = baseDao.findMapList(
					"select * from s_dic where opttype=? ", new Object[] { dic
							.get("OPTTYPE") });
			UniKeyValueObject uvo = new UniKeyValueObject();
			for (int j = 0; j < items.size(); j++) {
				Map<String, Object> sdic = items.get(j);
				uvo.addVariable(sdic.get("ENNAME").toString(), sdic.get(
						"CNNAME").toString());
			}
			dicBuffer.put(dic.get("OPTTYPE").toString().toUpperCase(), uvo);
		}
	}

	@Override
	public void terminate() {
		// 清除缓存
	}

	/**
	 * 根据指定字典项的名称，得到字典项的数据集合
	 * 
	 * @param dicName
	 * @return
	 */
	public UniKeyValueObject getValueList(String dicName) {
		return dicBuffer.get(dicName.toUpperCase());
	}

	/**
	 * 根据指定字典项的名称、字典项选项值来返回字典选项的描述
	 * 
	 * @param dicName
	 * @param dicOption
	 * @return
	 */
	public String getValueText(String dicName, String dicOption) {
		return dicBuffer.get(dicName.toUpperCase()).getValue(dicOption);
	}

}
